package dao

import (
	"fmt"
	"strconv"
	"strings"
	"yundian/internel/app/helper"
	"yundian/internel/app/models/regions"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
)

// -------------------- dao层 - 配置相关操作 -----------------------//

type SettingDao struct {

}

func NewSettingDao() *SettingDao {
	return &SettingDao{}
}

func (d *SettingDao) InsertRegion(result *regions.TencentRegionsResult) *dingo.ErrorWrap {
	lst := make([]*regions.RegionModel, 0)
	for _, value := range result.Result {
		for _, v := range value {
			cidx := helper.Int2Str(v.Cidx)
			pinyin := strings.Join(v.Pinyin, ",")
			m := &regions.RegionModel{
				RegionCode: v.ID,
				Name:       v.Name,
				FullName:   v.Fullname,
				Pinyin:     pinyin,
				Lat:        fmt.Sprintf("%.5f", v.Location.Lat),
				Lng:        fmt.Sprintf("%.5f", v.Location.Lng),
				Cidx:       cidx,
			}
			lst = append(lst, m)
		}
	}
	db := global.Orm.Table("lc_tencent_regions").Create(&lst)
	return dingo.ErrorIf(db.Error, true)
}

//func (d *SettingDao) InsertRegion(result [][]regions.Region) *dingo.ErrorWrap {
//	sqlStr := "INSERT INTO `lc_tencent_regions`(region_code,name,full_name,lat,lng,pinyin,cidx)VALUES"
//	vals := []interface{}{}
//	for _, value := range result {
//		for _, v := range value {
//			cidx := helper.Int2Str(v.Cidx)
//			pinyin := strings.Join(v.Pinyin, ",")
//			sqlStr += "(?,?,?,?,?,?,?),"
//			vals = append(vals, v.Id, v.Name, v.Fullname, fmt.Sprintf("%.5f", v.Location.Lat), fmt.Sprintf("%.5f", v.Location.Lng), pinyin, cidx)
//			//fmt.Println(v)
//		}
//	}
//	db := global.Orm.Exec(sqlStr, vals...)
//
//	//lst := make([]*regions.TencentRegions, 0)
//	//for _, value := range result {
//	//	for _, v := range value {
//	//		cidx := helper.Int2Str(v.Cidx)
//	//		pinyin := strings.Join(v.Pinyin, ",")
//	//		tencentRegions := &regions.TencentRegions{
//	//			RegionCode: v.Id,
//	//			Name:       v.Name,
//	//			RegionName: v.Fullname,
//	//			Lat:        v.Location.Lat,
//	//			Lng:        v.Location.Lng,
//	//			Pinyin:     pinyin,
//	//			Cidx:       cidx,
//	//		}
//	//		log.Println(tencentRegions)
//	//		lst = append(lst, tencentRegions)
//	//	}
//	//}
//	//db := global.Orm.Table("lc_tencent_regions").Create(&lst)
//	return dingo.ErrorIf(db.Error, db.RowsAffected)
//}

func (d *SettingDao) UpdateRegion(regexp, regexp2 string, offset, level int) *dingo.ErrorWrap {
	sql := "UPDATE `lc_tencent_regions` SET level = ?,parent_id = ? WHERE region_code REGEXP ? AND parent_id = 0 AND level = 0"

	if regexp2 == "" {
		db := global.Orm.Exec(sql, level, 0, regexp)
		return dingo.ErrorIf(db.Error, true)
	} else {
		lst := make([]*regions.RegionModel, 0)
		global.Orm.Raw("SELECT * FROM"+
			" `lc_tencent_regions` WHERE region_code REGEXP ?", regexp).Find(&lst)
		for _, l := range lst {
			reg,_ := strconv.Atoi(l.RegionCode)
			regexp := strconv.Itoa(reg/offset) + regexp2
			global.Orm.Exec(sql, level, l.ID, regexp)
		}
		return dingo.ErrorIf(nil, true)
	}
}
